package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import model.bean.EmpresaBean;

import Utils.StringUtil;

public class EmpresaDAO {

	public static void insertEmpresa(EmpresaBean empresa){
		Connection conn =  new MysqlConnect().connect();
		String sql = "INSERT INTO EMPRESA (RAZAOSOCIAL, CNPJ) VALUES(?,?)";
		try {
			PreparedStatement stmt = conn.prepareStatement(sql);
			stmt.setString(1, empresa.getRazaoSocial());
			stmt.setString(2, empresa.getCnpj());
			stmt.executeUpdate();
			conn.close();
		} catch (SQLException e) {
			System.out.println("Could not perform statement");
			e.printStackTrace();
		}
	}
	public static EmpresaBean getEmpresaByCnpj(String cnpj){
		MysqlConnect mysql = new MysqlConnect();
		String sql = "SELECT * FROM EMPRESA WHERE CNPJ = " + StringUtil.quotedStr(cnpj);
		ResultSet rs = mysql.executeQueryResult(sql);
		EmpresaBean empresa = null;
		try {
			while(rs.next()){
				int id = rs.getInt("idempresa");
				String nomeEmpresa = rs.getString("razaosocial");
				String cnpjEmpresa = rs.getString("cnpj");
				empresa = new EmpresaBean(nomeEmpresa, cnpjEmpresa);
				empresa.setIdEmpresa(id);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			mysql.desconnect();
		}
		return empresa;
	}
	public static int getId(String cnpj){
		MysqlConnect mysql = new MysqlConnect();
		String sql = "SELECT * FROM EMPRESA WHERE CNPJ = " + StringUtil.quotedStr(cnpj);
		ResultSet rs = mysql.executeQueryResult(sql);
		int id = 0;
		try {
			while(rs.next()){
				id = rs.getInt("idempresa");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			mysql.desconnect();
			return id;
		}
	}
}
